#include "MainFrame.h"
#include <fstream>
#ifdef _MSC_VER
#include <format>
#define fmt std
#else
#include <fmt/format.h>
#endif

#include "../../src/PixelFormat.h"
#include "../../src/SaveFile.cpp"
#include "../../src/SaveFile.h"
#include <iostream>

MainFrame::MainFrame() : wxFrame(nullptr, wxID_ANY, wxT("CCS解压程序")) {
  wxFlexGridSizer *mainSizer = new wxFlexGridSizer(2, 10, 10);
  mainSizer->SetSizeHints(this);
  mainSizer->AddGrowableCol(1, 1);
  dirpSourceDir =
      new wxDirPickerCtrl(this, (wxWindowID)MainFrameID::dirpSourceDir);
  dirpTargetDir =
      new wxDirPickerCtrl(this, (wxWindowID)MainFrameID::dirpTargetDir);
  btnStartDecomp = new wxButton(this, (wxWindowID)MainFrameID::btnStartDecomp,
                                wxT("开始解压"));
  mainSizer->Add(new wxStaticText(this, wxID_ANY, wxT("源目录")));
  mainSizer->Add(dirpSourceDir, wxSizerFlags(1).Expand());
  mainSizer->Add(new wxStaticText(this, wxID_ANY, wxT("目标目录")));
  mainSizer->Add(dirpTargetDir, wxSizerFlags(1).Expand());
  mainSizer->AddSpacer(0);
  mainSizer->Add(btnStartDecomp, wxSizerFlags(1).Expand());

  SetSizerAndFit(mainSizer);
  Bind(wxEVT_BUTTON, &MainFrame::on_btnStartDecomp_click, this,
       (int)MainFrameID::btnStartDecomp);
}

static std::list<std::filesystem::path> filename_css = {};

MainFrame::~MainFrame() {
  if (workThread.joinable())
    workThread.join();
}

void MainFrame::on_btnStartDecomp_click(wxCommandEvent &event) {
  wxProgressDialog progDlg(wxT("处理中"), wxT("正在扫描css文件"), 100, nullptr);
  filename_css.clear();
  SaveFile fileReader;
  // 验证用户输入
  if (dirpSourceDir->GetPath().length() == 0 ||
      dirpTargetDir->GetPath().length() == 0) {
    wxMessageBox(wxT("请选择文件读取/保存路径"), wxT("输入"), wxOK, this);
    return;
  }
  std::filesystem::path SourcePath, TargetPath;
  SourcePath = dirpSourceDir->GetPath().utf8_string();
  TargetPath = dirpTargetDir->GetPath().utf8_string();
  if (!std::filesystem::exists(SourcePath) ||
      !std::filesystem::exists(TargetPath)) {
    wxMessageBox(wxT("指定路径不存在"), wxT("错误"), wxOK, this);
    return;
  }
  for (auto const &dir_entry :
       std::filesystem::directory_iterator{SourcePath}) {
    std::string filePath = dir_entry.path().string();
    std::string file_suffix = filePath.substr(filePath.find_last_of('.') + 1);
    if (file_suffix == "ccs")
      filename_css.push_back(dir_entry.path());
  }
  auto listPtr = filename_css.cbegin();
  for (int j = 0; j < filename_css.size(); j++) {
    std::string newFileName = listPtr->filename().string();
    newFileName = newFileName.substr(0, newFileName.find_last_of('.'));
    std::filesystem::path newDir = TargetPath / newFileName;
    std::ifstream cssSource(listPtr->c_str(), std::ios::binary);
    int32_t imageWidth, imageHeight, frameCount;
    pixelFormat imgFormat;
    fileReader.StartReadImage(listPtr->string(), imageWidth, imageHeight,
                              frameCount, imgFormat);
    if (!cssSource.is_open()) {
      wxMessageBox(wxString::Format(L"文件打开失败: %s", listPtr->c_str()));
      return;
    }
    std::ofstream ofile(newDir, std::ios::trunc | std::ios::out);
    if (!ofile.is_open()) {
      wxMessageBox(wxT("无法创建输出文件"), wxT("错误"), wxOK, this);
      return;
    }
    unsigned char *imageData = nullptr;
    uint64_t timeStamp;
    long i = 0;

    while (true)
    // for(int i=0;i<frameCount;i++)
    {
      try {
        progDlg.Update(j, wxString::Format(L"正在处理存档：%d", j));
        fileReader.ReadImageWithTimestamp(imageData, timeStamp);
      } catch (const int &i) {
        // switch (i) {
        // case 1:
        //   wxMessageBox(wxT("提前遇到文件结尾，可能是数据残缺"),
        //   wxT("错误")); break;
        // case 2:
        //   wxMessageBox(wxT("无法正确解压数据，可能是数据残缺"),
        //   wxT("错误")); break;
        // }
        break;
      }
      ofile << i << ' ' << timeStamp << std::endl;
      delete[] imageData;
    }
    ofile.close();
    listPtr++;
  }
}
